package com.ruoyi.web.controller.energy;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.energy.service.IMqttMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * MQTT消息控制器
 * 
 * @author ruoyi
 * @date 2025-06-29
 */
@Api(tags = "MQTT消息管理")
@RestController
@RequestMapping("/energy/mqtt")
public class MqttController extends BaseController {

    @Autowired
    private IMqttMessageService mqttMessageService;

    /**
     * 发送MQTT消息
     */
    @ApiOperation("发送MQTT消息")
    @PreAuthorize("@ss.hasPermi('energy:mqtt:send')")
    @Log(title = "MQTT消息", businessType = BusinessType.OTHER)
    @PostMapping("/send")
    public AjaxResult sendMessage(
            @ApiParam("主题") @RequestParam String topic,
            @ApiParam("消息内容") @RequestParam String payload,
            @ApiParam("服务质量") @RequestParam(defaultValue = "1") int qos,
            @ApiParam("是否保留") @RequestParam(defaultValue = "false") boolean retained) {
        try {
            mqttMessageService.sendMessage(topic, payload, qos, retained);
            return AjaxResult.success("MQTT消息发送成功");
        } catch (Exception e) {
            logger.error("MQTT消息发送失败", e);
            return AjaxResult.error("MQTT消息发送失败: " + e.getMessage());
        }
    }

    /**
     * 订阅MQTT主题
     */
    @ApiOperation("订阅MQTT主题")
    @PreAuthorize("@ss.hasPermi('energy:mqtt:subscribe')")
    @Log(title = "MQTT订阅", businessType = BusinessType.OTHER)
    @PostMapping("/subscribe")
    public AjaxResult subscribe(
            @ApiParam("主题") @RequestParam String topic,
            @ApiParam("服务质量") @RequestParam(defaultValue = "1") int qos) {
        try {
            mqttMessageService.subscribe(topic, qos);
            return AjaxResult.success("MQTT主题订阅成功");
        } catch (Exception e) {
            logger.error("MQTT主题订阅失败", e);
            return AjaxResult.error("MQTT主题订阅失败: " + e.getMessage());
        }
    }

    /**
     * 取消订阅MQTT主题
     */
    @ApiOperation("取消订阅MQTT主题")
    @PreAuthorize("@ss.hasPermi('energy:mqtt:unsubscribe')")
    @Log(title = "MQTT取消订阅", businessType = BusinessType.OTHER)
    @PostMapping("/unsubscribe")
    public AjaxResult unsubscribe(@ApiParam("主题") @RequestParam String topic) {
        try {
            mqttMessageService.unsubscribe(topic);
            return AjaxResult.success("MQTT主题取消订阅成功");
        } catch (Exception e) {
            logger.error("MQTT主题取消订阅失败", e);
            return AjaxResult.error("MQTT主题取消订阅失败: " + e.getMessage());
        }
    }


}
